<template>
  <div class="container">
    <div class="app-container">
      <el-card class="box-card">
        <el-form ref="form" :model="queryInfo" label-width="80px" :inline="true">
          <el-row>
            <el-form-item label="关键字">
              <el-input placeholder="请输入关键字" v-model="queryInfo.keyword"></el-input>
            </el-form-item>
            <el-form-item label="状态：" width="100px">
              <el-select placeholder="请选择" v-model="queryInfo.state">
                <el-option label="启用" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="clearInfo">清除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchInfo">搜索</el-button>
            </el-form-item>
            <el-form-item style="float: right">
              <el-button type="success" icon="el-icon-edit" @click="addDialogVisible = true">新增数据</el-button>
            </el-form-item>
          </el-row>
        </el-form>
        <el-alert type="info" show-icon :closable="false" style="margin-bottom: 10px">共 {{ counts }} 条记录</el-alert>
        <!-- 渲染数据 -->
        <el-table stripe style="width: 100%" :data="articlesTableDate">
          <el-table-column prop="id" label="序号" width="100px"> </el-table-column>
          <el-table-column prop="title" label="文章标题" width="400px">
            <template slot-scope="scope">
              {{ scope.row.title }}
              <el-button type="text" icon="el-icon-video-camera" @click="videoOpen(scope.row)" v-if="scope.row.videoURL !== null"></el-button>
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数"> </el-table-column>
          <el-table-column prop="username" label="录入人"></el-table-column>
          <el-table-column prop="createTime" label="录入时间" :formatter="formateDate"></el-table-column>
          <el-table-column prop="state" label="状态" width="150px">
            <template slot-scope="scope">
              {{ scope.row.state === 1 ? '启用' : '禁用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="look(scope.row)">预览</el-button>
              <el-button type="text" @click="changeStatus(scope.row)">{{ scope.row.state === 1 ? '禁用' : '启用' }}</el-button>
              <el-button type="text" @click="showEditDialog(scope.row)" :disabled="scope.row.state === 0 ? true : false">修改</el-button>
              <el-button type="text" @click="deleteArt(scope.row)" :disabled="scope.row.state === 0 ? true : false">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页栏 -->
        <div class="block" style="margin: 15px; float: right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts"
          >
          </el-pagination>
        </div>
      </el-card>
      <!-- 新增数据弹出框 -->
      <el-dialog title="新增文章" :visible.sync="addDialogVisible" width="80%" center @close="closeAdd">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px" style="width: 90%; margin-left: 10px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addForm.title" autocomplete="off" placeholder="请输入文章标题"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <quill-editor v-model="addForm.articleBody" class="ql-editor"></quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" prop="videoURL">
            <el-input v-model="addForm.videoURL" autocomplete="off" placeholder="请输入视频地址"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAritcles">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 预览对话框 -->
      <el-dialog title="预览文章" :visible.sync="lookDialogVisible" width="50%">
        <div class="preview-box">
          <div class="preview-title">{{ articlesInfo.title }}</div>
          <div class="preview-nav">
            <span>{{ articlesInfo.createTime }}</span>
            <span>{{ articlesInfo.username }}</span>
            <span class="el-icon-view"></span>
            <span>{{ articlesInfo.visits }}</span>
          </div>
        </div>
        <div class="preview-content" v-html="articlesInfo.articleBody"></div>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog title="修改文章" :visible.sync="editDialogVisible" width="80%" center @close="closeEdit">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="120px" style="width: 90%; margin-left: 10px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="editForm.title" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <quill-editor v-model="editForm.articleBody" class="ql-editor"></quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" prop="videoURL">
            <el-input v-model="editForm.videoURL" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editArt">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 视频区域 -->
      <el-dialog :visible.sync="videoDialogVisible">
        <div class="input_video" style="width:100%;height:100%">
          <video v-if="videoDialogVisible" :src="articlesInfo.videoURL" controls style="width: 900px!important" autoplay>
          </video>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// import 'video.js/dist/video-js.css'

// import { videoPlayer } from 'vue-video-player'

import { list as ariList, add as artAdd, changeState as artChangeState, update as artUpdate, remove as artRemove } from '@/api/hmmm/articles.js'
export default {
  components: {
    quillEditor
    // videoPlayer
  },
  data () {
    return {
      loading: true,
      // 请求参数
      queryInfo: {
        // 当前页码
        page: 1,
        // 每页多少
        pagesize: 5,
        keyword: '',
        state: null
      },
      counts: 0,
      input: '',
      // 表格
      articlesTableDate: [],
      addDialogVisible: false,
      lookDialogVisible: false,
      editDialogVisible: false,
      videoDialogVisible: false,
      addForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 添加表单验证
      addFormRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        videoURL: [{ required: true, message: '请输入文章地址', trigger: 'blur' }]
      },
      // 点击当前预览的数据
      articlesInfo: [],
      // 编辑的数据
      editForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      }
      // videooo: ''
      // 视频播放
      // playerOptions: {
      //   playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选择的播放速度
      //   autoplay: false, // 如果true,浏览器准备好时开始回放。
      //   muted: false, // 默认情况下将会消除任何音频。
      //   loop: false, // 视频一结束就重新开始。
      //   preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
      //   language: 'zh-CN',
      //   aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
      //   fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
      //   sources: [
      //     {
      //       type: '',
      //       src: '' // url地址
      //     }
      //   ],
      //   poster: '', // 你的封面地址
      //   // width: document.documentElement.clientWidth,
      //   notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
      //   controlBar: {
      //     timeDivider: true, // 当前时间和持续时间的分隔符
      //     durationDisplay: true, // 显示持续时间
      //     remainingTimeDisplay: false, // 是否显示剩余时间功能
      //     fullscreenToggle: true // 全屏按钮
      //   }
      // }
    }
  },
  created () {
    this.getAritclesList()
  },
  methods: {
    /* 格式化日期 */
    formateDate (row, column, val, index) {
      var y = val.substr(0, 4)
      var m = val.substr(5, 2)
      var s = val.substr(8, 2)
      var hh = val.substr(11, 2)
      var mm = val.substr(14, 2)
      var ss = val.substr(17, 2)
      return `${y}-${m}-${s} ${hh}:${mm}:${ss}`
    },
    // ------------------------渲染列表-----------------------------
    // 获取面试技巧数据
    async getAritclesList () {
      try {
        const { data: res } = await ariList(this.queryInfo)
        this.articlesTableDate = res.items
        this.counts = res.counts
      } catch (error) {
        console.log(error)
      }
      // this.loading = false
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getAritclesList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (page) {
      this.queryInfo.page = page
      this.getAritclesList()
    },
    // 点击清除
    clearInfo () {
      this.queryInfo.keyword = ''
    },
    // 点击搜索
    searchInfo () {
      this.getAritclesList()
    },
    // ------------------------添加文章---------------------------
    async addAritcles () {
      // console.log(this.addFrom)
      try {
        await artAdd(this.addForm)
        // console.log(this.addForm)
        this.$message.success('添加文章成功')
        this.addDialogVisible = false
        this.getAritclesList()
      } catch (error) {
        this.$message.error('添加文章失败')
      }
    },
    closeAdd () {
      this.$refs.addFormRef.resetFields()
    },
    // -------------------------预览-------------------------------
    look (row) {
      this.articlesInfo = row
      console.log(this.articlesInfo)
      this.lookDialogVisible = true
    },
    // ------------------------修改状态-----------------------------
    changeStatus (data) {
      this.$confirm('是否切换状态？', '提示', {
        confirmButtonText: '确定',
        canceButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await artChangeState(data)
          this.$message.success(`已修改成功${data.state === 1 ? '禁用' : '启用'}`)
          this.getAritclesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消切换'
          })
        })
    },
    // ------------------------修改文章------------------------------
    // 弹出对话框
    showEditDialog (row) {
      this.editForm = row
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    closeEdit () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击提交
    editArt () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        try {
          const { data: res } = await artUpdate(this.editForm)
          console.log(res)
          this.getAritclesList()
          this.$message.success('编辑成功')
        } catch (error) {
          this.$message.success('编辑失败')
        }
        this.editDialogVisible = false
      })
    },
    // -------------------------删除文章-----------------------------
    deleteArt (row) {
      this.$confirm('此操作将永久删除改文章，是否继续？', '提示', {
        confirmButtonText: '确定',
        canceButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await artRemove(row)
          console.log(res)
          this.$message.success({ type: 'success', message: '删除成功' })
          this.getAritclesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // -------------------------视频播放-----------------------------
    videoOpen (row) {
      this.videoDialogVisible = true
      console.log(row)
      this.articlesInfo.videoURL = row.videoURL
    }
  }
}
</script>

<style scoped lang='less'>
/deep/.ql-editor {
  min-height: 200px !important;
  margin: -15px 0 0 -14px;
}
.preview-box {
  .preview-title {
    font-size: 25px;
    font-weight: 700;
    margin-bottom: 10px;
  }
  .preview-nav {
    span {
      margin-right: 10px;
    }
  }
  .preview-content {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f5f5;
    border-top: 1px dashed #ccc;
  }
}
.input_video {
  width: 400px;
  height: 400px;
  margin: 0 auto;
}
</style>
